{% extends "base.html" %}
{% block extrahead %}
{% endblock %}

{% block content %}
<script type="text/javascript" src="/js/gears_init.js"></script>
<script type="text/javascript" charset="utf-8">
  
var images = [];

var url = "/api/2008/01/01/01/01/01/0/";

function getImages() {
  document.getElementById('status').innerHTML = "fetching some more...";
  var the_object;
  var http_request = new XMLHttpRequest();
  http_request.open( "GET", url, true );
  http_request.onreadystatechange = function () {
    if ( http_request.readyState == 4 ) {
      if ( http_request.status == 200 ) {
        the_object = eval( "(" + http_request.responseText + ")" );
	url = the_object.next_url;
        images = images.concat(the_object.favicons);
	if (images.length > 0) {
           document.getElementById('status').innerHTML = "loading favicons!";
	} else {
           document.getElementById('status').innerHTML = "no new ones...";
	}
        loadImage();
        loadImage(++i);
        loadImage(++i);
        loadImage(++i);
        loadImage(++i);
      } else {
      }
        http_request = null;
    }
  };
  http_request.send(null);
}

getImages(url);
window.setInterval(function(){ getImages(url); }, 1000 * 30);

var i = 0;
var j = 0;
var images_loaded = 0;

// for production favicoop
var domains = ['favicoop.com', 'www.favicoop.com', '16x16.appspot.com', '16x16.favicoop.com'];
// for running locally
// var domains = ['localhost:8080'];

function loadImage() {
  var newImage = document.createElement('img');
  if (!images[i]) return; 
  newImage.src = 'http://' + domains[j++ % domains.length] +'/image/' + images[i];
  newImage.width = '16'
  newImage.height = '16'
  var retry = window.setTimeout(function(){
    loadImage(i);
  }, 5000)
  newImage.onload = onLoadClosure(newImage, retry);
}


function onLoadClosure(newImage, retry) {
  return function(){
    i++;
    images_loaded++;
    window.clearTimeout(retry);
    document.getElementById('accesses_block').appendChild(this);
    document.getElementById('count').innerHTML = images_loaded;
    loadImage(i);
  }
}

</script>

<div id="favicon_wrapper">
  <div id="stats">
  favicoop, a favicon collection | {{ favicon_cnt }} total | {{ favicon_today_cnt }} new today | {{ accesses_cnt }} accesses | {{ accesses_today_cnt }} accessed today | <a id="count">0</a> displayed | <a id"status"></a>
  </div>
  <div id="accesses_block">
  </div>
</div>

{% endblock %}
